$.star = {
    // 游戏字体图标
    gameIcon: function (appid) {
        var asGameFont = {
                "570": "&#xe815;",  //DOTA2
                "730": "&#xe816;",  //CS:GO
                "433850": "&#xe817;",   //H1Z1
                "440": "&#xe81b;",  //军团要塞2(TF2)
                "753": "&#xe819;",  //Steam
                "218620": "&#xe81c;",   //收获日2(Payday2)
                "578080": "&#xe818;",   //绝地求生(PUBG) 
                "295110": "&#xe81a;",   //Just Survive
                "360930": "&#xe6f2;",   //KF2
                "304930": "&#xe6f1;",   //Unturned
                "252490": "&#xe6f0;"  //Rust
            },
            sCurGameFont = ""
        ;

        for (var key in asGameFont) {
            if (key == appid) {
                sCurGameFont = asGameFont[key];
            }
        }

        return sCurGameFont;
    },
    http: function (oConfig) {
        var c5language = $.cookie('C5Lang')
        var langParams = ''

        if (c5language == 'tc' || c5language == 'zh') {
            langParams = 'zh-CN'
        } else {
            langParams = 'en-US'
        }

        var DEFAULT_CONFIG = {
            url: '',
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json',
            // processData: false,
            headers: {
                device: 1,
                platform: 2,
                'device-id': $.cookie('device_id'),
                'language': langParams
            },
            data: '',
            // warningConfig: '',  //未同意用户协议
            checkConfig: '',    //账号检测
            knowReceivingConfig: '',    //未开通自动收货助手
            // invalidReceivingConfig: '', //自动收货助手无效
            extraParamConfig: '',    //额外参数
            // 统一的成功处理方法
            success: function (res) {
                var code = parseInt(res.errorCode),
                    msg = res.errorMsg
                ;

                if (res && res.errorCode != 0) {
                    if (code == 101) {
                        // 未登录
                        if ($('#ajax-login-dailog').length > 0) {
                            $('#ajax-login-dailog').click()
                        } else {
                            window.location.href = '/login'
                        }
                    } else if (code == 106510) {
                        // 未绑定手机
                        require(["modal/bPhone"], function (phone) {
                            new phone({
                                successCallback: function () {
                                    if (oConfig.curAction) {
                                        oConfig.curAction.trigger("click");
                                    }
                                }
                            });
                        });
                    } else if (code == 106507) {
                        // 未绑定steam账号
                        require(["modal/dialog"], function (dialog) {
                            new dialog({
                                message: msg,
                                buttons: {
                                    btn1: {
                                        label: '立即绑定',
                                        className: 'btn btn-yellow btn-sm',
                                        callback: function () {
                                            window.location.href = "/api/link.json"
                                        }
                                    }
                                }
                            });
                        });
                    } else if (code == 106508) {
                        // 未绑定交易链接
                        require(["modal/bTradeLink"], function (tradeLink) {
                            new tradeLink({
                                steamId: oConfig.extraParamConfig.steamId,
                                successCallback: function () {
                                    if (oConfig.curAction) {
                                        oConfig.curAction.trigger("click");
                                    }
                                }
                            });
                        });
                    } else if (code == 106515) {
                        // 未设置API KEY
                        require(["modal/bApiKey"], function (apiKey) {
                            new apiKey({
                                steamId: oConfig.extraParamConfig.steamId,
                                successCallback: function () {
                                    if (oConfig.curAction) {
                                        oConfig.curAction.trigger("click");
                                    }
                                }
                            });
                        });
                    } else if (code == 107002) {
                        // 未设置支付密码
                        require(["modal/payPassword"], function (payPassword) {
                            new payPassword({
                                successCallback: function () {
                                    if (oConfig.curAction) {
                                        oConfig.curAction.trigger("click");
                                    }
                                }
                            });
                        });
                    } else if (code == 1000) {
                        // 未开通云服务
                        require(["modal/dialog"], function (dialog) {
                            new dialog({
                                message: '您需要开通卖家云服务能后才可使用此功能',
                                buttons: {
                                    btn1: {
                                        label: '取消',
                                        className: 'btn btn-blue btn-sm'
                                    },
                                    btn2: {
                                        label: '前往开通',
                                        className: 'btn btn-green btn-sm',
                                        callback: function () {
                                            window.location.href = "/user/cloudService.html";
                                        }
                                    }
                                }
                            });
                        });
                    } else if (code == 1404) {
                        // 云服务异常
                        require(["modal/dialog"], function (dialog) {
                            new dialog({
                                message: msg,
                                buttons: {
                                    btn1: {
                                        label: '取消',
                                        className: 'btn btn-blue btn-sm'
                                    },
                                    btn2: {
                                        label: '前去查看',
                                        className: 'btn btn-green btn-sm',
                                        callback: function () {
                                            window.location.href = "/user/cloudService.html";
                                        }
                                    }
                                }
                            });
                        });
                    } else if (code == 103011) {
                        // 账号检测
                        var oCheckConfig = {
                                isAuto: oConfig.checkConfig.isAuto || 1,
                                tipText: oConfig.checkConfig.tipText || '',
                                appId: '',
                                steamId: '',
                                type: oConfig.checkConfig.type || 1,
                                currBuyBtn: '',
                                optType: oConfig.checkConfig.optType || 1,
                                successCallback: oConfig.checkConfig.successCallback || null
                            }
                        ;

                        if (oConfig.checkConfig.curAction) {
                            oCheckConfig.currBuyBtn = oConfig.checkConfig.curAction;
                        } else if (oConfig.curAction) {
                            oCheckConfig.currBuyBtn = oConfig.curAction;
                        } else {
                            oCheckConfig.currBuyBtn = $(this);
                        }

                        if (res.errorData && res.errorData.appId) {
                            oCheckConfig.appId = res.errorData.appId;
                        } else if (oConfig.checkConfig.appId) {
                            oCheckConfig.appId = oConfig.checkConfig.appId;
                        }

                        if (res.errorData && res.errorData.steamId) {
                            oCheckConfig.steamId = res.errorData.steamId;
                        } else if (oConfig.checkConfig.steamId) {
                            oCheckConfig.steamId = oConfig.checkConfig.steamId;
                        }

                        $.checkAccount(oCheckConfig);

                        $(".gx-modal-hideAction").modal("hide");
                    } else if (code == 3106) {
                        // 未开通自动收货助手
                        require(["modal/knowReceiving"], function (knowReceiving) {
                            new knowReceiving({
                                type: oConfig.knowReceivingConfig.type || '',
                                successCallback: function () {
                                    if (oConfig.curAction) {
                                        oConfig.curAction.trigger("click");
                                    }
                                }
                            });
                        });
                    }

                    console.log('httpError-----', msg);
                }
            },
            // 统一的异常处理方法
            error: function (response) {
                var status = parseInt(response.status);

                // 按钮恢复正常状态
                if (oConfig.curAction) {
                    oConfig.curAction.button('reset');
                }
            }
        };

        oConfig.url = '/gw' + oConfig.url;
        oConfig = $.extend(true, DEFAULT_CONFIG, oConfig);
        var secTime = new Date().getTime() + ''
        var ranNum = randomNum(1000000, 9999999) + ''
        if (typeof oConfig.data == 'string') {
            if (oConfig.data.length <= 0) {
                oConfig.data = {}
                oConfig.data.reqId = secTime + ranNum
            }
        } else {
            oConfig.data.reqId = secTime + ranNum
        }
        if (oConfig.type == 'POST') {
            oConfig.url = oConfig.url + '?reqId=' + secTime + ranNum
            oConfig.data = JSON.stringify(oConfig.data)
        }

        return ajax = $.ajax(oConfig);
    },
    getHttpErrCode: function (code) {
        var bIsPass = true;

        if (code == 101 ||
            code == 106510 ||
            code == 106507 || code == 106508 || code == 106515 ||
            code == 107002 ||
            code == 1000 ||
            code == 1404 ||
            code == 103011 ||
            code == 3106
        ) {

            bIsPass = false;

        } else {

            bIsPass = true;

        }

        return bIsPass;
    },
    // ajax
    ajax: function (oConfig) {
        var DEFAULT_CONFIG = {
            contentType: 'application/x-www-form-urlencoded',
            url: '',
            type: 'GET',
            dataType: 'json',
            data: '',
            warningConfig: '',  //未同意用户协议
            checkConfig: '',    //账号检测
            knowReceivingConfig: '',    //未开通自动收货助手
            invalidReceivingConfig: '', //自动收货助手无效
            // 统一的成功处理方法
            success: function (res) {
                var code = parseInt(res.status),
                    msg = res.message
                ;

                if (code == 1027) {
                    // 未同意用户协议
                    require(["modal/riskWarning"], function (riskWarning) {
                        var oWarningConfig = {
                            type: oConfig.warningConfig.type || 'buy'
                        };

                        new riskWarning({
                            type: oWarningConfig.type,
                            successCallback: function () {
                                if (oConfig.curAction) {
                                    oConfig.curAction.trigger("click");
                                }
                            }
                        });
                    });
                } else if (code == 1024) {
                    // 未绑定手机
                    require(["modal/bPhone"], function (phone) {
                        new phone({
                            successCallback: function () {
                                if (oConfig.curAction) {
                                    oConfig.curAction.trigger("click");
                                }
                            }
                        });
                    });
                } else if (code == 3000) {
                    // 未绑定steam账号
                    require(["modal/dialog"], function (dialog) {
                        new dialog({
                            message: msg,
                            buttons: {
                                btn1: {
                                    label: '立即绑定',
                                    className: 'btn btn-yellow btn-sm',
                                    callback: function () {
                                        window.location.href = "/api/link.json"
                                    }
                                }
                            }
                        });
                    });
                } else if (code == 3010) {
                    // 未绑定交易链接
                    require(["modal/bTradeLink"], function (tradeLink) {
                        new tradeLink({
                            successCallback: function () {
                                if (oConfig.curAction) {
                                    oConfig.curAction.trigger("click");
                                }
                            }
                        });
                    });
                } else if (code == 3020 || code == 3021) {
                    // 未设置API KEY或API KEY无效
                    require(["modal/bApiKey"], function (apiKey) {
                        new apiKey({
                            successCallback: function () {
                                if (oConfig.curAction) {
                                    oConfig.curAction.trigger("click");
                                }
                            }
                        });
                    });
                } else if (code == 1026) {
                    // 未设置支付密码
                    require(["modal/payPassword"], function (payPassword) {
                        new payPassword({
                            successCallback: function () {
                                if (oConfig.curAction) {
                                    oConfig.curAction.trigger("click");
                                }
                            }
                        });
                    });
                } else if (code == 9999) {
                    // 未开通云服务
                    require(["modal/dialog"], function (dialog) {
                        new dialog({
                            message: '您需要开通卖家云服务能后才可使用此功能',
                            buttons: {
                                btn1: {
                                    label: '取消',
                                    className: 'btn btn-blue btn-sm'
                                },
                                btn2: {
                                    label: '前往开通',
                                    className: 'btn btn-green btn-sm',
                                    callback: function () {
                                        window.location.href = "/user/cloudService.html";
                                    }
                                }
                            }
                        });
                    });
                } else if (code == 8000 || code == 8100 || code == 8200 || code == 8300 || code == 8400 || code == 8500) {
                    // 云服务异常
                    require(["modal/dialog"], function (dialog) {
                        new dialog({
                            message: msg,
                            buttons: {
                                btn1: {
                                    label: '取消',
                                    className: 'btn btn-blue btn-sm'
                                },
                                btn2: {
                                    label: '前去查看',
                                    className: 'btn btn-green btn-sm',
                                    callback: function () {
                                        window.location.href = "/user/cloudService.html";
                                    }
                                }
                            }
                        });
                    });
                } else if (code == 3104) {
                    // 账号检测
                    var oCheckConfig = {
                            isAuto: oConfig.checkConfig.isAuto || 1,
                            tipText: oConfig.checkConfig.tipText || '',
                            appId: oConfig.checkConfig.appId || '',
                            type: oConfig.checkConfig.type || 1,
                            currBuyBtn: '',
                            optType: oConfig.checkConfig.optType || 2
                        }
                    ;

                    if (oConfig.checkConfig.curAction) {
                        oCheckConfig.currBuyBtn = oConfig.checkConfig.curAction;
                    } else if (oConfig.curAction) {
                        oCheckConfig.currBuyBtn = oConfig.curAction;
                    } else {
                        oCheckConfig.currBuyBtn = $(this);
                    }

                    if (res.body && res.body.appId) {
                        oCheckConfig.appId = res.body.appId;
                    } else if (oConfig.checkConfig.appId) {
                        oCheckConfig.appId = oConfig.checkConfig.appId;
                    }

                    if (res.body && res.body.steamId) {
                        oCheckConfig.steamId = res.body.steamId;
                    } else if (oConfig.checkConfig.steamId) {
                        oCheckConfig.steamId = oConfig.checkConfig.steamId;
                    }

                    $.checkAccount(oCheckConfig);

                    $(".gx-modal-hideAction").modal("hide");
                } else if (code == 3106) {
                    // 未开通自动收货助手
                    require(["modal/knowReceiving"], function (knowReceiving) {
                        new knowReceiving({
                            type: oConfig.knowReceivingConfig.type || '',
                            successCallback: function () {
                                if (oConfig.curAction) {
                                    oConfig.curAction.trigger("click");
                                }
                            }
                        });
                    });
                } else if (code == 3107) {
                    // 自动收货助手无效
                    require(["modal/invalidReceiving"], function (invalidReceiving) {
                        new invalidReceiving({
                            type: oConfig.invalidReceivingConfig.type || '',
                            successCallback: function () {
                                if (oConfig.curAction) {
                                    oConfig.curAction.trigger("click");
                                }
                            }
                        });
                    });
                } else if (code == 3108) {
                    // 发货授权无效
                    require(["modal/steamLogin"], function (steamLogin) {
                        new steamLogin({
                            // type: oConfig.invalidReceivingConfig.type || '',
                            successCallback: function () {
                                if (oConfig.curAction) {
                                    oConfig.curAction.trigger("click");
                                }
                            }
                        });
                    });
                }
            },
            // 统一的异常处理方法
            error: function (response) {
                var status = parseInt(response.status);

                // 按钮恢复正常状态
                if (oConfig.curAction) {
                    oConfig.curAction.button('reset');
                }
            }
        };

        oConfig = $.extend(true, DEFAULT_CONFIG, oConfig);
        var secTime = new Date().getTime() + ''
        var ranNum = randomNum(1000000, 9999999) + ''
        if (typeof oConfig.data == 'string') {
            if (oConfig.data.length <= 0) {
                oConfig.data = {}
                oConfig.data.reqId = secTime + ranNum
            }
        }

        return ajax = $.ajax(oConfig);
    },
    getPublicErrCode: function (code) {
        var bIsPass = true;

        if (code == 1027 ||
            code == 1024 ||
            code == 3000 || code == 3010 || code == 3020 || code == 3021 ||
            code == 1026 ||
            code == 9999 ||
            code == 8000 || code == 8100 || code == 8200 || code == 8300 || code == 8400 || code == 8500 ||
            code == 3104 ||
            code == 3106 || code == 3107
        ) {

            bIsPass = false;

        } else {

            bIsPass = true;

        }

        return bIsPass;
    },
    /**
     * 获取验证码
     *
     * @param {jQuery} el 操作对象
     * @param {Number} count 倒计时时间
     * @param {String} noClass 不可点击类名
     * @param {String} accessText 倒计时文案
     * @param {String} resetText 倒计时结束文案
     *
     * @return {void}
     */
    setCodeTime: function (el, count, noClass, accessText, resetText) {
        var count = count || 60,
            noClass = noClass || "noClick",
            accessText = accessText || "秒后重发",
            resetText = resetText || "重新发送",

            nInterval = null,
            ACCESS_CODE_STYLE = count + accessText
        ;

        el.html(ACCESS_CODE_STYLE).addClass("noClick");
        nInterval = setInterval(function () {
            ACCESS_CODE_STYLE = (count - 1) + accessText;

            el.html(ACCESS_CODE_STYLE).addClass("noClick");

            if (count == 1) {
                el.html(resetText).removeClass("noClick");
                clearInterval(nInterval);
            } else {
                count--;
            }
        }, 1000);
    },
    // 获取图形验证码
    getVerifyDom: function (el, sUrl) {
        $.star.ajax({
            url: sUrl,
        }).then(function (res) {
            el.attr("src", res.url);
        });
    },
    // 输入校验是否为数字,两位小数
    checkNumber: function (str) {
        var re = /^\d+\.?\d{0,2}$/;

        if (re.test(str) && str.length < 10) {

            return true;
        } else {
            return false;
        }
    },
    // 3位数字加一个逗号
    formatNumber: function (str) {
        return (str + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
    },
    formatPrice: function (str) {
        return str.replace(/[^\d|.]/g, '');
    },
    // 格式化日期
    formatDate: function (timestamp) {
        var timestamp = Number(timestamp),
            time = new Date(timestamp);
        year = time.getFullYear(),
            month = time.getMonth() + 1,
            date = time.getDate()
        ;

        return year + '.' + $.star.addZero(month) + '.' + $.star.addZero(date);
    },
    // 补0
    addZero: function (num) {
        return num < 10 ? '0' + num : num;
    },
    // 判断值是否为空
    isNull: function (str) {
        if (str == null || str == 'undefined' || str == '' || str.length == 0) {
            return true;
        } else {
            return false;
        }
    },
    alertDanger: function (body_dom, msg) {
        if (msg && body_dom.length >= 1) {
            var html = '';
            var error_dom = $('.body-error-message');
            if (error_dom.length == 0) {
                html += '<div class="alert alert-danger body-error-message">' + msg + '</div>';

                body_dom.prepend(html);
            } else {
                error_dom.text(msg);
            }
        }
    },
    clearAlert: function () {
        var error_dom = $('.body-error-message');

        if (error_dom.length > 0) {
            error_dom.remove();
        }
    },
    page: function (count, limit, current_page, page_dom) {
        var str = "";
        current_page = parseInt(current_page);
        var pre_page = current_page - 1 ? current_page - 1 : 1;
        var show_size = 5;//显示5个li
        var total_size = count % limit == 0 ? parseInt(count / limit) : (parseInt(count / limit) + 1);//总页数
        var next_page = current_page == total_size ? total_size : current_page + 1;
        var pageActive;
        var n = 2;
        if (count > limit) {//数量大于限制显示分页
            show_size = show_size > total_size ? total_size : show_size;
            str += '<li class="page first"><a href="javascript:void(0)" page-no="1">首页</a></li><li class="page prev"><a page-no="' + pre_page + '" href="javascript:void(0);">上一页</a></li>';
            if (current_page < show_size / 2 + 1) {
                for (var i = 1; i <= show_size; i++) {
                    if (i == current_page) {
                        pageActive = 'page active';
                    } else {
                        pageActive = 'page';
                    }
                    str += '<li class="' + pageActive + '"><a page-no="' + i + '" href="javascript:void(0);">' + i + '</a></li>';
                }
            } else {
                var start;
                var end;
                // console.log(1111)
                if (total_size < show_size + current_page) {
                    start = total_size - show_size + 1;
                    end = total_size;
                } else {
                    start = current_page - n;
                    end = current_page + show_size - n;
                }
                // console.log(start,end)
                for (var i = start; i <= end; i++) {
                    if (i == current_page) {
                        pageActive = 'page active';
                    } else {
                        pageActive = 'page';
                    }
                    str += '<li class="' + pageActive + '"><a page-no="' + i + '" href="javascript:void(0);">' + i + '</a></li>';
                }
            }
            str += '<li class="page next"><a page-no="' + next_page + '" href="javascript:void(0);">下一页</a></li><li class="page last"><a href="javascript:void(0)" page-no="' + total_size + '">尾页</a></li>';
        }

        page_dom.html(str);
    },
    getLoginUserId: function () {
        var uid = 0;

        $.ajax({
            async: false,
            dataType: 'json',
            type: 'GET',
            url: '/api/login/isLogin',
            success: function (res) {

                uid = res.body.value;
            }
        });

        return uid;
    },
    // 改变当前URL参数
    changeURLPar: function (destiny, par, par_value) {
        var pattern = par + '=([^&]*)';
        var replaceText = par + '=' + par_value;

        if (destiny.match(pattern)) {
            var tmp = '/\\' + par + '=[^&]*/';
            tmp = destiny.replace(eval(tmp), replaceText);
            return (tmp);
        } else {

            if (destiny.match('[\?]')) {
                return destiny + '&' + replaceText;
            } else {
                return destiny + '?' + replaceText;
            }
        }
        return destiny + '\n' + par + '\n' + par_value;
    },
    lazyLoadTemplate: function ($dom) {

        if ($dom.data('load') == 1) return;

        if ($dom.data('pagination')) {
            //开启分页
            $dom.pagination({
                requestUrl: $dom.data('url'),
                templateId: $dom.data('lazy-tpl'),
                dataContainer: $dom,
                enableUrlPage: $dom.data('enable-page') == 1
            });
        } else {
            if ($dom.data('interface') == 'http') {
                $.star.http({
                    url: $dom.data('url')
                }).then(function (res) {
                    var nCode = res.errorCode,
                        sMsg = res.errorMsg
                    ;

                    if (nCode == 0) {
                        if ($dom.data('escape') == "1") {
                            template.config('escape', false);
                        }

                        var html = template($dom.data('lazy-tpl'), res);

                        $dom.html(html);

                        $dom.data('load', 1);
                    }
                });
            } else {
                $.ajax({
                    url: $dom.data('url'),
                    dataType: "jsonp",
                    success: function (json) {

                        if ($dom.data('escape') == "1") {
                            template.config('escape', false);
                        }

                        var html = template($dom.data('lazy-tpl'), json);

                        $dom.html(html);

                        $dom.data('load', 1);
                    }
                });
            }
        }
    },
    getUrlParams: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURIComponent(r[2]);
        return null;
    },
    changeUrlParams: function (name, value) {
        var oUrl = window.location.href.toString();
        var re = eval('/(' + name + '=)([^&]*)/gi');
        var nUrl = oUrl.replace(re, name + '=' + value);
        return nUrl;
    },
    countDown: function ($dom) {
        //倒计时
        if ($dom.length > 0) {
            $.each($dom, function (k, v) {
                var $this = $(this);
                var expired_time = $this.attr('data-expired-time');
                var now_time = $this.data('now-time');
                var refresh = $this.data('refresh');
                var diff_time = parseInt(expired_time - now_time);
                if (diff_time > 0) {
                    var b0 = Math.floor(diff_time / 60 / 10);
                    var b1 = Math.floor(diff_time / 60) - b0;
                    var b2 = Math.floor((diff_time % 60) / 10);
                    var b3 = (diff_time % 60) % 10;
                    var b4 = 0;
                    var b5 = 0;
                    k = window.setInterval(function () {
                        if (b5 < 0) {
                            b4 = b4 - 1;
                            b5 = 9;
                        }
                        if (b4 < 0) {
                            b3 = b3 - 1;
                            b4 = 9;
                        }
                        if (b3 < 0) {
                            b2 = b2 - 1;
                            b3 = 9;
                        }
                        if (b2 < 0) {
                            b1 = b1 - 1;
                            b2 = 5;
                        }
                        if (b1 < 0) {
                            b0 = b0 - 1;
                            b1 = 9;
                        }
                        $this.find('b').eq(0).html(b0);
                        $this.find('b').eq(1).html(b1);
                        $this.find('b').eq(2).html(b2);
                        $this.find('b').eq(3).html(b3);
                        $this.find('b').eq(4).html(b4);
                        $this.find('b').eq(5).html(b5);
                        b5--;
                        if (b0 == 0 && b1 == 0 && b2 == 0 && b3 == 0 && b4 == 0 && b5 == 0) {
                            clearInterval(k);
                            if (refresh == 1) {
                                setTimeout(function () {
                                    window.location.reload();
                                }, 500);
                            } else {
                                $this.find('.announce-show').hide();
                                $this.find('.countdown-ing').show();
                                $this.find('.jiexiao').remove();
                            }
                        }
                    }, 10);
                } else {

                    $this.find('.announce-show').hide();

                    $this.find('.countdown-ing').show();

                    $this.find('.jiexiao').remove();

                    $this.find('.yijiexiao').removeClass("hide");
                }
            });
        }
    },
    zhimaCheckVerify: function (name, message, success, error) {
        $.get(Config.BaseUrl + '/api/zhiMa/checkverify', name ? {realname: name} : null, function (res) {
            if (res.status != 200) {
                var $button = [
                    {
                        text: c5_modal_cancel,
                        class: 'btn-blue btn-sm'
                    },
                    {
                        text: '前往认证',
                        class: 'btn-orange btn-sm',
                        callback: function () {
                            window.location.href = Config.BaseUrl + '/user/verify.html';
                        }
                    }
                ];

                if (res.status == 511) {
                    $button[0].text = c5_modal_button_confirm;
                    $button[1].text = '查看进度';
                } else if (res.status == 512) {
                    $button = [{
                        text: c5_modal_button_confirm,
                        class: 'btn-green btn-sm'
                    }]
                }
                var modal = $.showMessage({
                    content: typeof message == 'string' ? message : res.message,
                    close: true,
                    buttons: $button
                });
                error && error(modal);
                return;
            }
            var callback = success;
            if (typeof message == 'function') {
                callback = message;
            }
            callback && callback();
        });
    },
    getSellerLevel: function (type) {
        // 用户等级+卖家等级
        var asSellerLevel = [];

        $('[data-seller-level]').each(function () {
            var jThis = $(this),
                sThisSellerLevel = jThis.data('seller-level')
            ;

            asSellerLevel.push(sThisSellerLevel);
        });

        if (asSellerLevel && asSellerLevel[0]) {
            $.star.ajax({
                type: 'POST',
                url: '/api/user/sellerLevel',
                data: {
                    user_id: asSellerLevel
                }
            }).then(function (res) {
                var nCode = res.status,
                    sMsg = res.message
                ;

                if (nCode == 200) {
                    var oData = res.body;

                    for (var i = 0; i < oData.length; i++) {
                        $('[data-seller-level]').each(function () {
                            var jThis = $(this),
                                sThisUserId = Number(oData[i].userId),
                                sThisSellerLevel = Number(jThis.data('seller-level'))
                            ;

                            if (sThisUserId == sThisSellerLevel) {
                                if (type == 'user') {
                                    jThis.addClass('level-' + oData[i].sellerUserLevel);
                                } else {
                                    jThis.addClass('level' + oData[i].sellerLevelInfo.level);
                                }
                            }
                        })
                    }
                }
            })
        }
    },
    addition: function (arg1, arg2) {
        // 加法函数
        var r1, r2, m;
        try {
            r1 = arg1.toString().split(".")[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        return (arg1 * m + arg2 * m) / m;
    },
    subtraction: function (arg1, arg2) {
        // 减法函数
        var r1, r2, m, n;
        try {
            r1 = arg1.toString().split(".")[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        // last modify by deeka
        // 动态控制精度长度
        n = (r1 >= r2) ? r1 : r2;
        return ((arg1 * m - arg2 * m) / m).toFixed(n);
    },
    multiplication: function (arg1, arg2) {
        // 乘法函数
        var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
        try {
            m += s1.split(".")[1].length;
        } catch (e) {
        }
        try {
            m += s2.split(".")[1].length;
        } catch (e) {
        }
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    },
    division: function (arg1, arg2) {
        // 除法函数
        var t1 = 0, t2 = 0, r1, r2;
        try {
            t1 = arg1.toString().split(".")[1].length;
        } catch (e) {
        }
        try {
            t2 = arg2.toString().split(".")[1].length;
        } catch (e) {
        }
        with (Math) {
            r1 = Number(arg1.toString().replace(".", ""));
            r2 = Number(arg2.toString().replace(".", ""));
            return (r1 / r2) * pow(10, t2 - t1);
        }
    },
    numFormat: function (num1, num2, operator) {
        var tempNum = 0,

            decimal = 2,
            decimalArr = [],
            decimalLength = 0
        ;

        if (operator == 'multiplication') {
            tempNum = $.star.multiplication(num1, num2);
        } else if (operator == 'division') {
            tempNum = $.star.division(num1, num2);
        }

        decimalArr = tempNum.toString().split(".");
        if (decimalArr.length > 1 && decimalArr[1].length > decimal) {
            decimalLength = parseInt(decimalArr[1].substring(decimal, decimal + 1));
        }

        tempNum = $.star.division(Math.floor($.star.multiplication(tempNum, 100)), 100);
        if (decimalLength > 0) {
            return $.star.addition(tempNum, 0.01);
        } else {
            return tempNum;
        }
    }
};

//: 返回顶端
$(document).on('click', '#scroll-up', function () {
    $('html, body').animate({
        scrollTop: 0
    }, 1000);
});
$(window).scroll(function () {
    var $this = $(this);
    if ($this.scrollTop() < 100) {
        $('#scroll-up').fadeOut();
    } else if ($('#scroll-up').is(':hidden')) {
        $('#scroll-up').fadeIn();
    }
});

//tab标签切换时加载图片
$(document).on('click', 'li', function () {
    $(window).trigger('scroll');
});

$(document).on('keypress', '.disabled-enter', function (event) {
    if (event.which == 13) {
        return false;
    }
});
$(document).on('blur', '.sell-sale-input, .sell-actual-input', function () {
    $(this).val(Number($(this).val()))
})

$(document).on('keyup', '.sell-input , .sell-sale-input, .sell-actual-input, #discount-val , .value-input, .inputfix , .batch-price , #input-money  , input[name="money"] ', function (e) {
    var obj = {};
    obj.value = $(this).val();
    obj.value = obj.value.replace(/[^\d.]/g, "");
    obj.value = obj.value.replace(/^0[\d]/g, "0");
    if (!$(this).hasClass('sell-sale-input') && !$(this).hasClass('sell-actual-input')) {
        obj.value = obj.value.replace(/^\./g, "");
    }
    obj.value = obj.value.replace(/\.{2,}/g, ".");
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    var decimal = 0;
    if ($(this).data('decimal') == 'purchase') {
        var value = $(this).val();
        if (value < 1) {
            decimal = 2;
        } else if (value <= 100) {
            decimal = 1;
        } else if (value > 100) {
            decimal = 0;
            obj.value = parseInt(obj.value).toString();
        }
    } else {
        decimal = parseInt($(this).data('decimal')) || 2;
    }
    var decimalReg = ''
    for (var i = 1; i <= decimal; i++) {
        decimalReg += '\\d';
    }
    obj.value = obj.value.replace(new RegExp('^(\\-)*(\\d+)\\.(' + decimalReg + ').*$'), '$1$2.$3');
    $(this).val(obj.value);

})

// 设置支付密码
$(document).on('click', '.set-pay-pwd-btn', function () {
    var patrn = /^[0-9]*$/;
    var pwd = $('#pay-pwd').val();
    var repwd = $('#pay-repwd').val();
    var url = $(this).data('url');
    if (!patrn.test(pwd)) {
        ZENG.msgbox.show("密码必须为纯数字");
    } else {
        if (pwd.length === 6) {
            if (pwd === repwd) {
                var data = {
                    'paypwd': pwd,
                    'confirm_paypwd': repwd,
                };
                $.post(url, data).success(function (res) {
                    $("#set-paypwd-modal").modal('hide');
                    $.showMessage({'content': res.message, refresh: true});
                }).error(function (res) {
                    $.showMessage({'content': res.message});
                })
            } else {
                ZENG.msgbox.show("两次密码输入不一致")
            }
        } else {
            ZENG.msgbox.show("密码应为6位数字")
        }
    }
});
$(document).on('click', '.change-pay-pwd-btn', function () {
    var patrn = /^[0-9]*$/;
    var pwd = $('#pay-pwd-change').val();
    var repwd = $('#pay-repwd-change').val();
    var url = $(this).data('url');
    var code = $('#pwd-modal-verify').val();

    var paypwdModal = $(this).parents('#change-paypwd-modal');

    if (paypwdModal.find("#J_Verify").length > 0 && !paypwdModal.find("#J_Verify").val()) {
        ZENG.msgbox.show("请输入图形验证码");
    } else if (!patrn.test(pwd)) {
        ZENG.msgbox.show("密码必须为纯数字");
    } else {
        if (pwd.length === 6) {
            if (pwd === repwd) {
                if (patrn.test(code) && code.length == 6) {
                    var data = {
                        'paypwd': pwd,
                        'confirm_paypwd': repwd,
                        'code': code,
                    };
                    $.post(url, data).success(function (res) {
                        $("#set-paypwd-modal").modal('hide');
                        $.showMessage({'content': res.message, refresh: true});
                    }).error(function (res) {
                        $.showMessage({'content': res.message});
                    })
                } else if (code.length == 0) {
                    ZENG.msgbox.show("请输入手机验证码")
                } else {
                    ZENG.msgbox.show("手机验证码应为6位纯数字")
                }
            } else {
                ZENG.msgbox.show("两次密码输入不一致")
            }
        } else {
            ZENG.msgbox.show("密码应为6位数字")
        }
    }

}).on('focus', '[data-input-type-change]', function () {
    if (this.tagName != 'INPUT') {
        return;
    }
    var changeType = $(this).data('inputTypeChange');
    if (changeType == $(this).attr('type')) {
        return;
    }
    $(this).attr('type', changeType);
});

$(document).on("keyup", '.sell-input', function () {
    var $this = $(this);
    if ($this.val() > 1000000) {
        $this.val(0)
    }
});
// 语言选择
$(document).on('click', '#q_Msgbox', function () {
    $(this).css({'display': 'none'})
});
$(document).on('mouseenter ', '.language-select', function () {
    $('.language-chose-body').css('height', '93px')
    $('.language-up').css('opacity', '1')

})
$(document).on('mouseleave', '.language-select', function () {
    $('.language-chose-body').css('height', '0px')
    $('.language-up').css('opacity', '0')
})
$(function () {
    if ($.cookie('C5Lang') == 'zh' && $('body').css('font-family') != 'tc') {
        $('.language-chose-body').find('.zchinese').addClass('active')
        $('.language-select .language-select-text').text('简中')
    } else if ($('body').css('font-family') == 'tc') {
        $('.language-chose-body').find('.tchinese').addClass('active')
        $('.language-select .language-select-text').text('繁中')
    }
})

// 新首页提示
$(document).on('click', '#new-home .shut', function () {
    $('#new-home').hide();
    $.cookie('C5NewHome', 1);
});

function opensteam(url, type) {
    var winObj = window.open(url, 'newwindow', 'height = 800, width = 700');
    var loop = setInterval(function () {

        if (winObj.closed && type != 1) {
            clearInterval(loop);
            parent.location.reload();
        }
    }, 1);
    var urlto = ""
    if (type == 0) {
        urlto = window.location.origin + '/api/passport/steam.json?proxy_switch=2'
    } else if (type == 1) {
        urlto = Config.C5SteamHost + '/my/tradeoffers/privacy'
    } else if (type == 2) {
        urlto = window.location.origin + '/api/link.json?proxy_switch=2'
    } else if (type == 3) {
        urlto = Config.C5SteamHost + 'dev/apikey'
    } else if (type == 4) {
        urlto = Config.C5SteamHost + url.slice(27, url.length)
    }
    if (false) {
        $.showMessage({
            title: '系统提示',
            width: 512,
            content: 'steam页面打不开？</br>建议使用C5GAME提供的优化线路，点击可<a href="#" class="ft-gold steamurltochange">直接访问</a>',
            buttons: [
                {
                    text: '知道了',
                    class: 'btn btn-blue',
                    dismiss: true,
                    callback: function () {
                        if ($('#issteamurltochange').prop('checked')) {
                            $.cookie("C5Steamurl", "true", {expires: 10, path: "/"});
                        }
                    }
                }
            ],
            before: function ($modal) {
                $modal.find('.modal-footer').append('<label class="ml-10 pull-left"><input type="checkbox" style="position: relative;top: 2px;" id="issteamurltochange" /> <span>不再提示 </span></label>');

            }
        })
        $('.steamurltochange').on('click', function () {
            winObj.location.href = urlto
            winObj.focus()
        })
    }

}

$(document).on('click', '.steamurlchoselink', function () {
    var url = $(this).data('url');
    opensteam(url, 1)
    return false;
})
$(document).on('click', '.steamurlchose', function () {
    var url = $(this).data('url');
    opensteam(url, 3)
    return false;
})
$(document).on('click', '#steam-link', function () {
    var url = $(this).data('url');
    opensteam(url, 2)
    return false;
})
$(document).on('click', '.steamurlchosebuy', function () {
    var url = $(this).data('url');
    opensteam(url, 4)
    return false;
})
$(function () {
    if ($('.container>.top-notice-common').length > 0) {
        var sNoticeid = '';

        $.star.ajax({
            url: '/api/notice',
        }).then(function (res) {
            if (res.status == 200) {
                var noticeList = res.body.list,
                    shownoticelist = []
                ;

                if (localStorage.C5Noticelist) {
                    var C5Noticelist = JSON.parse(localStorage.C5Noticelist);

                    for (var i = 0; i < noticeList.length; i++) {
                        if ($.inArray(noticeList[i].id, C5Noticelist) == -1) {
                            shownoticelist.push(noticeList[i]);
                        }
                    }
                } else {
                    shownoticelist = noticeList;
                }

                if (shownoticelist.length != 0) {
                    $('.container>.top-notice').html(template('top-notice-tpl', res));
                    $('#slidershow').carousel();
                }

                if ($('#J_GxNoticeModal').length > 0) {
                    for (var i = 0; i < noticeList.length; i++) {
                        if (noticeList[i].is_popup == 1) {
                            if ($.cookie('C5NoticeBounces' + noticeList[i].id) == null) {
                                $('#J_GxNoticeModal .notice-message').html(noticeList[i].msg);

                                if (noticeList[i].url != '') {
                                    $('#J_GxNoticeModal .notice-href').attr('href', noticeList[i].url);
                                    $('#J_GxNoticeModal .notice-know').addClass('hide');
                                    $('#J_GxNoticeModal .notice-href').removeClass('hide')
                                }

                                $('body').append($('#J_GxNoticeModal'));
                                $('#J_GxNoticeModal').modal('show');

                                sNoticeid = noticeList[i].id;
                            }
                        }
                        break
                    }
                }
            }
        });

        $('#J_GxNoticeModal').on('hidden.bs.modal', function () {
            $.cookie('C5NoticeBounces' + sNoticeid, 'close', {expires: 7});
        });
    }
})
const wsConnect = function () {
    var ws = new WebSocket(window.Config.WEBSCOKETHOST + '?user_id=' + window.Config.UID);

    ws.onopen = function (evt) {

    };

    ws.onmessage = function (evt) {
        var res = JSON.parse(evt.data)
        var $grabLuckyModal = $('#grabLuckyModal')
        var $recoveryprice = res.recovery_price
        $grabLuckyModal.find('.grabLucky-item .csgo-img-bg img').attr('src', res.image_url)
        $grabLuckyModal.find('#grabLucky-name').text(res.itemName)
        $grabLuckyModal.find('#grabLucky-date').text(res.expire_time)
        $grabLuckyModal.find('.grabLuckyModal-coinnum').text(Number($recoveryprice.toFixed(2)))
        $grabLuckyModal.modal('show')
        if (res.exterior_name != '') {
            $grabLuckyModal.find('.grabLucky-type').removeClass('hide')
            $grabLuckyModal.find('.grabLucky-type').text(res.exterior_name)
            $grabLuckyModal.find('.grabLucky-type').css('color', res.exterior_color)
        } else {
            $grabLuckyModal.find('.grabLucky-type').addClass('hide')
        }
    };

    ws.onclose = function (evt) {
        setTimeout(function () {
            wsConnect()
        }, 3000)
    };
}
if (window.Config && window.Config.UID > 0) {
    // wsConnect()
}
$(document).on('click', ' .indexMobileGuide-btn .iconfont', function () {
    $(this).closest('#indexMobileGuide').addClass('hide')
    $.cookie('C5MobileGuide', 1, {expires: 1, path: '/'});
})


if (window.Config && window.Config.UID && window.Config.UID != 0) {
    $.star.http({url: '/steamtrade/offer/v1/wait-list'}).then(
        function (res) {
            if (res.errorCode != 0) {
                return false
            }
            if (res.data) {
                let num = res.data.offerIds.length
                localStorage.setItem('offerIds', JSON.stringify(res.data.offerIds));
                statisticsActiveorder(num)
            } else {
                statisticsActiveorder(0)
                localStorage.setItem('offerIds', '[]');

                if (res.data && res.data.isAddNew == 1) {
                    $('.trend-bell').addClass('animation')
                    setTimeout(() => {
                        $('.trend-bell').removeClass('animation')
                    }, 1000)
                }
            }

        }
    )
}

function statisticsActiveorder(num) {
    $.star.http({
        type: 'GET',
        url: '/steamtrade/trade-order-operation/v1/active-order',
        data: {
            platformId: 2,
            userId: Config.UID
        }
    })
        .then(function (res) {
            if (res.data) {
                for (var z = 0; z < res.data.length; z++) {
                    if (res.data[z].type != 5) {
                        num++
                    }
                }
            } else {

            }
            if (num > 0) {
                offerdata = res.data
                $('.trend-num').removeClass('hide')
                $('.trend-num').text(num)
                if (num >= 100) {
                    $('.trend-num').text('99+')
                }
            } else {
                $('.trend-num').addClass('hide')
            }
        }, function (req) {

        })
}

function getWebsockforOffer() {
    window.newIframe = null;

    $.star.ajax({
        url: '/api/user/zbtToken'
    }).then(function (res) {
        var option = {
            iframeEle: "body",
            webUrl: Config.trade_ws,
            push_token: getCookie('C5AToken'),
            lang: window.Config.Lang == 'zh' ? 'zh-CN' : 'en-US',
            url: Config.quoteHost,
            userId: Config.UID,
            platformId: '2',
            zbtToken: res.body.token
        };
        window.newIframe = new getIframe(option);
        $(document).on('click', '.tradeTrend', function () {
            window.newIframe.zbtquote('show')
            return false
        });
        $(document).on('click', '#zbtQuote-modal-backdrop', function () {
            window.newIframe.zbtquote('hide')
            if (location.href.indexOf('login') <= -1) {
                $.star.http({
                    url: '/steamtrade/offer/v1/wait-list'
                }).then(
                    res => {
                        if (res.errorCode != 0) {
                            return false
                        }
                        if (res.data) {
                            let num = res.data.offerIds.length
                            localStorage.setItem('offerIds', JSON.stringify(res.data.offerIds));
                            statisticsActiveorder(num)
                        } else {
                            statisticsActiveorder(0)
                            localStorage.setItem('offerIds', '[]');

                            if (res.data && res.data.isAddNew == 1) {
                                $('.trend-bell').addClass('animation')
                                setTimeout(() => {
                                    $('.trend-bell').removeClass('animation')
                                }, 1000)
                            }
                        }

                    }
                )
            }
        })
    })

}

if (window.Config && location.href.indexOf('login') <= -1 && location.href.indexOf('quote') <= -1 && location.href.indexOf('order/pay') <= -1 && location.href.indexOf('csgoview') <= -1) {

    if (window.Config.UID > 0) {
        getWebsockforOffer()
    }

}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 0;
            break;
    }
}

// function add (num1, num2) {
//     var e =  Math.pow(10, Math.max(getDecimalLength(num1), getDecimalLength(num2)))
//     return (mul(num1, e) + mul(num2, e)) / e
// }
// function sub(num1, num2) {
//     var e =  Math.pow(10, Math.max(getDecimalLength(num1), getDecimalLength(num2)))
//     return (mul(num1, e) - mul(num2, e)) / e
// }
// function mul (num1, num2) {
//     var c = 0,
//         d = num1 + '',
//         e = num2 + ''
//     try {
//         c += getDecimalLength(num1)
//     } catch(err) {}
//     try {
//         c += getDecimalLength(num2)
//     } catch(err) {}
//     return Number(d.replace('.', '')) * Number(e.replace('.', '')) / Math.pow(10, c)
// }
// function div (num1, num2) {
//     var a = num1
//     var b = num2
//     num1 += ''
//     num2 += ''
//     return mul(Number(num1.replace('.', '')) / Number(num2.replace('.', '')), Math.pow(10, getDecimalLength(a) - getDecimalLength(b)))
// }
// function getDecimalLength (num) {
//     num += ''
//     try {
//         return num.split(".")[1].length;
//     } catch (e) {
//         return 0
//     }
// }
// function feeFormat (price, rate) {
//     if (!price || !rate) {
//         console.error('no price or feeRate ---->from function=>priceFormat')
//         return false
//     }
//     var fee = mul(price, rate)
//     var scale = 2
//     var numArr = fee.toString().split(".")
//     var scaleNum = 0
//     if (numArr.length > 1 && numArr[1].length > scale) {
//         scaleNum = parseInt(numArr[1].substring(scale, scale + 1));
//     }
//     var tempFee = div(Math.floor(mul(fee, 100)), 100)
//     if (scaleNum > 0 ) {
//         return add(tempFee,0.01)
//     } else {
//         return tempFee
//     }
// }






